package com.guxingke.nioserver.core;

import com.guxingke.nioserver.exception.ServerException;
import com.guxingke.nioserver.event.ServerListener;

import java.util.ArrayList;

public class Notifier {
    private static ArrayList<ServerListener> listeners = null;
    private static Notifier instance = null;

    private Notifier() {
        listeners = new ArrayList<ServerListener>();
    }

    public static synchronized Notifier getNotifier() {
        if (instance == null) {
            instance = new Notifier();
            return instance;
        } else
            return instance;
    }

    public void addListener(ServerListener l) {
        synchronized (listeners) {
            if (!listeners.contains(l))
                listeners.add(l);
        }
    }

    public void fireOnAccept() throws Exception {
        for (int i = listeners.size() - 1; i >= 0; i--)
            ((ServerListener) listeners.get(i)).onAccept();
    }

    public void fireOnAccepted(HttpRequest request) throws Exception {
        for (int i = listeners.size() - 1; i >= 0; i--)
            ((ServerListener) listeners.get(i)).onAccepted(request);
    }

    void fireOnRead(HttpRequest request) throws Exception {
        for (int i = listeners.size() - 1; i >= 0; i--)
            ((ServerListener) listeners.get(i)).onRead(request);

    }

    void fireOnWrite(HttpRequest request, HttpResponse response)
            throws Exception {
        for (int i = listeners.size() - 1; i >= 0; i--)
            ((ServerListener) listeners.get(i)).onWrite(request, response);

    }

    public void fireOnClosed(HttpRequest request) throws Exception {
        for (int i = listeners.size() - 1; i >= 0; i--)
            ((ServerListener) listeners.get(i)).onClosed(request);
    }

    public void fireOnError(ServerException serverException) {
        for (int i = listeners.size() - 1; i >= 0; i--)
            ((ServerListener) listeners.get(i)).onError(serverException);
    }
}
